package vn.pyco.prez.tapestry.components;

import java.io.File;
import java.util.List;

import org.apache.tapestry5.ComponentResources;
import org.apache.tapestry5.SymbolConstants;
import org.apache.tapestry5.annotations.AfterRender;
import org.apache.tapestry5.annotations.Import;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.SessionAttribute;
import org.apache.tapestry5.annotations.SetupRender;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.ioc.annotations.InjectService;
import org.apache.tapestry5.ioc.annotations.Symbol;
import org.apache.tapestry5.services.javascript.JavaScriptSupport;

import vn.pyco.prez.PrezConstants;
import vn.pyco.prez.PrezConstants.Steps;
import vn.pyco.prez.dao.DaoManager;
import vn.pyco.prez.model.Slide;
import vn.pyco.prez.tapestry.pages.Index;
import vn.pyco.prez.tapestry.services.AppHelper;
import vn.pyco.prez.tapestry.tasks.ConvertionTask;
import vn.pyco.prez.tapestry.tasks.ConvertionTaskFactory;

@Import(
	stack=PrezConstants.COMETD_JSSTACK,
	library={
			"${prez.scripts}/jquery.cometd.settings.js",
			"${prez.scripts}/jquery.cometd.prezgenerator.js"
	}
)
public class PrezGenerator {
	@SuppressWarnings("unused")
	@SessionAttribute(PrezConstants.SESSION_STEP)
	private Steps _currentStep;
	
	@Inject
	private JavaScriptSupport _jsSupport;
	
	@Inject
	private AppHelper _appHelper;
	
	@Inject
    private ComponentResources _resources; 

	@Inject
	@Symbol(SymbolConstants.PRODUCTION_MODE)
	private boolean _productionMode;
	
	@SessionAttribute(PrezConstants.SESSION_SELECTED_FILE)
	private File _selectedFile;
	
	@SuppressWarnings("unused")
	@SessionAttribute(PrezConstants.SESSION_TASK_ID)
	private String _taskId;
	
	@InjectService("taskManager")
	private DaoManager<ConvertionTask> _taskManager;
	
	@InjectService("slideManager")
	private DaoManager<List<Slide>> _slideManager;

	private ConvertionTask _convertTask;
	
	@SetupRender
	public void setupRender(){
    	_convertTask = ConvertionTaskFactory.getConvertionTask(_selectedFile,_slideManager);
		_taskManager.save(_convertTask.getId(), _convertTask);
		_taskId = _convertTask.getId();
	}
	
	@AfterRender
	public void afterRender(){
		_jsSupport.addScript("CometSettings.init('%s','%s','%s','%s');",
				_appHelper.getFQNRootUrl(Boolean.FALSE) + PrezConstants.COMETD_URL,
				_productionMode ? "warn" : "info",
				_convertTask.getId(),
				_resources.createEventLink("showprez").toURI()
				);
		_jsSupport.addScript("CometPresentation.init();");
	}
	
	@OnEvent(value="showprez")
	public Class<?> showPresentation(){
		_currentStep = Steps.SHOW;
		return Index.class;
	}

}
